package com.module.ble.utils

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.os.Build
import android.os.CountDownTimer
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import com.common.app.data.bean.KeyPre
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.app.utls.TimeUtils.getTimeZone
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnNewThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.getContext
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.postDelay
import com.common.base.app.extras.postIoDelay
import com.common.base.app.extras.removeSpacesAndNewlines
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils.getApplication
import com.common.base.utils.AppUtils.getPackageName
import com.common.base.utils.JsonUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.ToastUtils
import com.eiot.aizo.sdk.callback.AizoDeviceConnectCallback
import com.eiot.ringsdk.ServiceSdkCommandV2
import com.eiot.ringsdk.be.DeviceManager
import com.eiot.ringsdk.bean.HealthDataBean
import com.eiot.ringsdk.bean.SleepRecord
import com.eiot.ringsdk.bean.SportLiveData
import com.eiot.ringsdk.bean.SportRecord
import com.eiot.ringsdk.bean.SportStatus
import com.eiot.ringsdk.callback.BCallback
import com.eiot.ringsdk.callback.HealthDataCallback
import com.eiot.ringsdk.callback.ICallback
import com.eiot.ringsdk.callback.SleepDataCallback
import com.eiot.ringsdk.callback.SportLiveDataCallback
import com.eiot.ringsdk.callback.SportRecordCallback
import com.eiot.ringsdk.callback.SportStatusCallback
import com.eiot.ringsdk.measure.MeasureResult
import com.eiot.ringsdk.measure.MeasureResultCallback
import com.eiot.ringsdk.score.ActivityGoals
import com.eiot.ringsdk.score.ActivityGoalsCallback
import com.jiaqiao.product.ext.toFastJson
import com.module.ble.data.bean.RingInfoBean
import com.module.ble.db.table.UserAcLevel
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserCalorie
import com.module.ble.db.table.UserEnvTemperature
import com.module.ble.db.table.UserHealthIntegratedData
import com.module.ble.db.table.UserHeartEntryTime
import com.module.ble.db.table.UserHeartRate
import com.module.ble.db.table.UserHrv
import com.module.ble.db.table.UserRespiratoryRate
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.db.table.UserSportRecord
import com.module.ble.db.table.UserStand
import com.module.ble.db.table.UserStepsRelatedRecord
import com.module.ble.db.table.UserStress
import com.module.ble.hDu.HDActionReceiver
import com.module.ble.hDu.HDBleService
import com.module.ble.hDu.HDCommonAttributes
import com.module.ble.hDu.HDServiceImpl
import com.module.ble.hDu.HDuSendCommandManage
import com.module.ble.hDu.SportMonitorTask
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.listener.CusBleDeviceInfoExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.listener.CusSdkSettingExpandListener
import com.module.ble.listener.CusSportMonitorDataExpandListener
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.BodyTemperatureRepo
import com.module.ble.repo.HealthIntegratedDataRepo
import com.module.ble.repo.HeartEntryTimeRepo
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.HeartRateVariabilityRepo
import com.module.ble.repo.RespiratoryRateRepo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.repo.UserAcLevelRepo
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.repo.UserStandRepo
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.repo.UserStressRepo
import com.module.ble.yQi.YQiSendCommandManage
import com.sxr.sdk.ble.keepfit.aidl.IRemoteService
import com.sxr.sdk.ble.keepfit.aidl.IServiceCallback
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeout
import net.grandcentrix.tray.AppPreferences
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.atomic.AtomicBoolean

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2024/10/17
 *
 * 描述：研强sdk 初始化工具
 *
 * 修订历史：
 *
 */
object AizoSDKUtil {
    private const val TAG = "AizoSDKInitUtil"

    //    private val serviceSdkCommand by lazy { ServiceSdkCommand }
    private var serviceSdkCommand: ServiceSdkCommandV2? = null

    val mConnectBleDeviceExpandListenerList =
        CopyOnWriteArrayList<CusConnectBleDeviceExpandListener>()
    val mBleDeviceInfoExpandListenerList =
        CopyOnWriteArrayList<CusBleDeviceInfoExpandListener>()
    val mCusSynthesisHealthExpandListenerList =
        CopyOnWriteArraySet<CusSynthesisHealthExpandListener>()
    val mSportMonitorDataExpandListenerList =
        CopyOnWriteArraySet<CusSportMonitorDataExpandListener>()

    var isConnect = ConnectState.STATE_DISCONNECTED //0已断开1连接中2已连接

    var macTemp: String? = null//临时选中的mac
    var curMac: String? = null//当前设备mac
    var curElectricity: String = ""//电量
    var curWorkingMode = 0//工作状态
    var curRingInfoBean: RingInfoBean? = null

    private var mConnectedMacId: String? = null
    private val bSaveLog = true
    var sharedPreferences: AppPreferences? = null
    var mHDuService: IRemoteService? = null
    private var mHduActionReceiver: HDActionReceiver? = null
    private var mHduServiceCallback: IServiceCallback? = null
    private var mHDuServiceConnection: ServiceConnection? = null
    private var mHDuServiceConnectionConnecting = false//华嘟SDK初始化中
    var mServiceConnectionFirst = true//首次连接
    private var mCurrentSyncDays: Int = -1

    // 查询锁，防止并发查询
    val queryYQMultiDaysHealthDataLock = AtomicBoolean(false)
    private const val QUERY_TIMEOUT = 30000L // 30秒超时

    private val processingDays = mutableSetOf<Long>()
    private val queryLock = Mutex()

    var mHduSportMonitorTask: SportMonitorTask? = null

    init {
        curMac = getBleBindingMac()
        curRingInfoBean = getBindRingInfo()
    }

    /**
     * 校验SDK服务是否为空
     */
    fun checkInitServiceSdk(ringFirm: String): Boolean {
        when (ringFirm) {
            DeviceFirmType.YQ_FIRM -> {
                if (serviceSdkCommand != null) return false
            }

            DeviceFirmType.HDU_FIRM -> {
                return if (mHDuService == null) {
                    LogUtils.e(TAG, "checkInitServiceSdk: mHDuService = null")
                    false
                } else {
                    true
                }
            }
        }
        return false
    }

    /**
     * SDK初始化
     */
    fun initAizoServiceSdk(mRingFirm: String?) {
        if (mRingFirm.isNullOrEmpty()) return
        (mRingFirm == DeviceFirmType.HDU_FIRM).yes {
            initHuaDuServiceSdk(mRingFirm)
        }.otherwise {
            if (mHDuServiceConnectionConnecting) return
            mHDuServiceConnectionConnecting = true

            if (serviceSdkCommand != null) return
            serviceSdkCommand = ServiceSdkCommandV2
            serviceSdkCommand?.init(
                getApplication(),
                region = 1,
                version = "1.0.0",
                name = "SDK_DEMO_APP",
                id = getPackageName(),
                country = "CN",
                language = "ZH",
                debugging = true
            )
            serviceSdkCommand?.addCallback(object : AizoDeviceConnectCallback {
                override fun connect() {
                    mHDuServiceConnectionConnecting = false
                    Log.e(TAG, "YQ: connectBleDevice-connect")
                    isConnect = ConnectState.STATE_CONNECTED
                    mConnectBleDeviceExpandListenerList.forEach {
                        curMac = macTemp
                        it.onConnect(curMac)
                    }
                    curMac?.let { curMacIt ->
                        mServiceConnectionFirst.yes {
                            mServiceConnectionFirst = false
                            serviceSdkCommand?.notifyBoundDevice("", curMacIt, object : BCallback {
                                override fun result(r: Boolean) {
                                    Log.e(TAG, "YQ: notifyBoundDevice-result:$r")
                                }
                            })
                        }
                    }
                    getDevicePowerState()
                }

                override fun connectError(throwable: Throwable, state: Int) {
                    mHDuServiceConnectionConnecting = false
                    Log.e(TAG, "YQ: connectBleDevice-connectError:${throwable}")
                    Log.e(TAG, "YQ: connectBleDevice-connectError:msg-${throwable.message}")
                    isConnect = ConnectState.STATE_DISCONNECTED
                    mConnectBleDeviceExpandListenerList.forEach {
                        it.onConnectError(curMac, throwable, state)
                    }
                }

                override fun disconnect() {
                    mHDuServiceConnectionConnecting = false
                    Log.e(TAG, "YQ: connectBleDevice-disconnect")
                    isConnect = ConnectState.STATE_DISCONNECTED
                    mConnectBleDeviceExpandListenerList.forEach {
                        it.onDisconnect(curMac)
                    }
                }
            })

            //注册其他状态监听
            YQiSendCommandManage.registerOtherListener(serviceSdkCommand)
        }
    }

    /**
     * 初始化华嘟SDK
     */
    fun initHuaDuServiceSdk(mRingFirm: String) {
        if (mHDuServiceConnectionConnecting) return
        mHDuServiceConnectionConnecting = true

        LogUtils.e(TAG, "HDu-sdk initHuaDuServiceSdk->start")
        mHduServiceCallback = HDServiceImpl()

        mHDuServiceConnection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                mHDuServiceConnectionConnecting = false
                mHDuService = IRemoteService.Stub.asInterface(service)
                try {
                    mHDuService?.registerCallback(mHduServiceCallback)
                    mHDuService?.openSDKLog(bSaveLog, HDCommonAttributes.P_LOG_PATH, "demo.log")

                    val isConnected = HDuSendCommandManage.callRemoteIsConnected(mHDuService)
                    val authorize: Int = HDuSendCommandManage.callRemoteIsAuthorize(mHDuService)
                    Log.i(
                        TAG,
                        "HDu-onServiceConnected -> isConnected=$isConnected, authorize=$authorize"
                    )
                    if (authorize == 200) {
                        LogUtils.e(TAG, "HDu-sdk authorize succcess=$authorize")
                        mServiceConnectionFirst.yes {
                            mServiceConnectionFirst = false
                            if (macTemp.isNullOrEmpty()) return
                            isConnect().no {
                                LogUtils.e(TAG, "HDu-sdk isConnect：=$isConnect")
                                mHDuService?.connectBt(mRingFirm, macTemp)
                            }
                        }
                        if (isConnected) {
                            mConnectedMacId =
                                HDuSendCommandManage.callRemoteGetConnectedDevice(mHDuService)
                            // 获取已连接上的蓝牙设备地址
                        }
                    } else {
                        onDestroyRingSdk()
                        LogUtils.e(TAG, "HDu-sdk authorize failed=$authorize")
                        mConnectBleDeviceExpandListenerList.forEach {
                            doOnUiThread { it.onBoundDeviceResult("", false) }
                        }
                    }
                } catch (e: RemoteException) {
                    LogUtils.e(TAG, "HDu-sdk onServiceConnected=RemoteException")
                    onDestroyRingSdk()
                    e.printStackTrace()
                    mConnectBleDeviceExpandListenerList.forEach {
                        doOnUiThread { it.onBoundDeviceResult("", false) }
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName) {
                onDestroyRingSdk()
                LogUtils.e(TAG, "HDu-sdk onServiceDisconnected: ${name.toString()}")
            }
        }

        getContext().apply {
            sharedPreferences = AppPreferences(this)

            registerReceiver(this)
            val gattServiceIntent = Intent(this, HDBleService::class.java)

            mHDuServiceConnection?.let { serviceConnectionIt ->
                // 启动蓝牙服务
                this.bindService(gattServiceIntent, serviceConnectionIt, Context.BIND_AUTO_CREATE)
            }
        }
    }

    /**
     * SDK注销
     */
    fun onDestroyRingSdk(removeListener: Boolean = false) {
        mConnectBleDeviceExpandListenerList.forEach {
            it.onDisconnect(curMac)
        }
        removeListener.yes {
            BleOtherUtil.removeThreadLocalCalendar()
            removeAllConnectBleDeviceExpandListener()
        }
        YQiSendCommandManage.clearOtherListener(serviceSdkCommand)//注销其他状态监听
        disconnectBle()
        serviceSdkCommand?.onDestory()
        serviceSdkCommand = null
        mHDuServiceConnectionConnecting = false
        onDestroHuaDuSdk()
        isConnect = ConnectState.STATE_DISCONNECTED
    }

    /**
     * 注销华嘟SDK
     */
    fun onDestroHuaDuSdk() {
        LogUtils.e(TAG, "HDu-sdk onDestroHuaDuSdk->start")
        HDuSendCommandManage.callRemoteDisconnect(mHDuService)
        mHduActionReceiver?.apply {
            getContext().unregisterReceiver(this)
        }
        mHDuServiceConnection?.apply {
            getContext().unbindService(this)
        }
        mHduServiceCallback?.apply {
            try {
                mHDuService?.unregisterCallback(this)
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }
        mHduActionReceiver = null
        mHDuService = null
        mHDuServiceConnection = null
        mHduServiceCallback = null
        mServiceConnectionFirst = true
        queryYQMultiDaysHealthDataLock.set(false)

    }

    private fun registerReceiver(context: Context) {
        mHduActionReceiver = HDActionReceiver(mHDuService)
        val intentFilter = IntentFilter()
        intentFilter.addAction(HDBleService.ECG_SWITCH)
        intentFilter.addAction(HDBleService.FACTORYMODE_TEST_SWITCH)
        intentFilter.addAction(HDCommonAttributes.ACTION_NOTIFY_CLASSIC_BT_NEED_CONNECT)
        intentFilter.addAction(HDCommonAttributes.ACTION_NOTIFY_CLASSIC_BT_RETRY_BOND)
        intentFilter.addAction(HDCommonAttributes.ACTION_NOTIFY_CLASSIC_BT_CREATE_BOND)
        intentFilter.addAction(HDCommonAttributes.ACTION_REQUEST_DIAL_JSON_CONTENT)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            context.registerReceiver(mHduActionReceiver, intentFilter, Context.RECEIVER_EXPORTED)
            context.registerReceiver(
                mHduActionReceiver,
                intentFilter,
                Context.RECEIVER_VISIBLE_TO_INSTANT_APPS
            )
        } else {
            context.registerReceiver(mHduActionReceiver, intentFilter)
        }
    }

    fun setElectricityInfo(electricity: Int, workingMode: Int) {
        Log.e(
            TAG,
            "电量:" + electricity + "%" + "\n" + "状态:" + when (workingMode) {
                0 -> "未充电"
                1 -> "充电中"
                else -> "未充电"
            }
        )
        if (electricity > 0) {
            curRingInfoBean?.ringElectricity = electricity
            curRingInfoBean?.eleUpTime = getTimeDateLong()
        }
        updateRingInfo()
        curElectricity = electricity.toString()
        curWorkingMode = workingMode
        mBleDeviceInfoExpandListenerList.forEach {
            doOnUiThread { it.onDevicePowerState(curElectricity, curWorkingMode) }
        }
    }

    /**
     * 添加蓝牙设备连接回调
     */
    fun addConnectBleDeviceExpandListener(
        listener: CusConnectBleDeviceExpandListener,
        index: Int? = null
    ) {
        (index == null).yes { mConnectBleDeviceExpandListenerList.add(listener) }
            .otherwise { mConnectBleDeviceExpandListenerList.add(0, listener) }
    }

    /**
     * 移除蓝牙设备连接回调
     */
    fun removeConnectBleDeviceExpandListener(listener: CusConnectBleDeviceExpandListener) {
        mConnectBleDeviceExpandListenerList.remove(listener)
    }

    /**
     * 添加蓝牙设备信息回调
     */
    fun addBleDeviceInfoExpandListener(listener: CusBleDeviceInfoExpandListener) {
        mBleDeviceInfoExpandListenerList.add(listener)
    }

    /**
     * 移除蓝牙设备设备信息回调
     */
    fun removeBleDeviceInfoExpandListener(listener: CusBleDeviceInfoExpandListener) {
        mBleDeviceInfoExpandListenerList.remove(listener)
    }

    /**
     * 添加蓝牙设备健康信息回调
     */
    fun addSynthesisHealthExpandListener(listener: CusSynthesisHealthExpandListener) {
        mCusSynthesisHealthExpandListenerList.add(listener)
    }

    /**
     * 添加运动回调
     */
    fun addSportMonitorDataExpandListener(listener: CusSportMonitorDataExpandListener) {
        mSportMonitorDataExpandListenerList.add(listener)
    }

    /**
     * 移除蓝牙设备健康信息回调
     */
    fun removeSynthesisHealthExpandListener(listener: CusSynthesisHealthExpandListener) {
        mCusSynthesisHealthExpandListenerList.remove(listener)
    }

    /**
     * 移除运动回调
     */
    fun removeSportMonitorDataExpandListener(listener: CusSportMonitorDataExpandListener) {
        mSportMonitorDataExpandListenerList.remove(listener)
    }

    /**
     * 移除所有蓝牙设备相关回调监听
     */
    fun removeAllConnectBleDeviceExpandListener() {
        mCusSynthesisHealthExpandListenerList.clear()
        mConnectBleDeviceExpandListenerList.clear()
        mBleDeviceInfoExpandListenerList.clear()
        mSportMonitorDataExpandListenerList.clear()
    }

    /**
     * 蓝牙设备及缓存信息
     */
    fun removeBleDeviceInfoInApp() {
        curMac = ""
        macTemp = ""
        isConnect = ConnectState.STATE_DISCONNECTED
        curElectricity = ""
        curWorkingMode = 0
        SpUtilsManagement.removeFromKey(KeyPre.KEY_RING_MAC)
        SpUtilsManagement.removeFromKey(KeyPre.KEY_RING_FIRM)
        SpUtilsManagement.removeFromKey(KeyPre.KEY_RING_INFO)
        SpUtilsManagement.removeFromKey(KeyPre.KEY_HAS_REPORT_DEVICE)
        mConnectBleDeviceExpandListenerList.forEach {
            it.onHandleDevice(2, true)
        }
    }

    /**
     * 蓝牙连接请求
     */
    @Synchronized
    fun connectBleDevice(macStr: String, ringFirm: String) {
        if (macStr.isNullOrEmpty()) return
        macTemp = macStr
        isConnect().no {
            when (ringFirm) {
                DeviceFirmType.YQ_FIRM -> {
                    LogUtils.e(TAG, "YQ: sdk connectBt")
                    serviceSdkCommand?.connect(macTemp!!)
                }

                DeviceFirmType.HDU_FIRM -> {
                    try {
                        LogUtils.e(TAG, "HDu-sdk connectBt")
                        doOnIOThread { mHDuService?.connectBt(ringFirm, macTemp) }
                    } catch (e: RemoteException) {
                        LogUtils.e(TAG, "HDu-sdk connectBt->RemoteException")
                        onDestroyRingSdk()
                        e.printStackTrace()
                    }
                }

                else -> {}
            }
        }
    }

    /**
     * 蓝牙连接请求
     */
    @Synchronized
    fun connectBleAndInitDevice(macStr: String, ringFirm: String) {
        if (macStr.isNullOrEmpty()) return
        macTemp = macStr

        var time = 100L
        checkInitServiceSdk(ringFirm).no {
            initAizoServiceSdk(ringFirm)
            time = 4000L //  延时4秒
        }

        postDelay(time) {
            connectBleDevice(macStr, ringFirm)
        }
    }

    /**
     * 蓝牙连接请求
     */
    @Synchronized
    fun disconnectBle() {
        serviceSdkCommand?.disconnect(object : BCallback {
            override fun result(r: Boolean) {
            }

        })
    }

    fun isConnect(): Boolean {
//        if (getBleBindingMac().isNullOrEmpty()) return false
        return isConnect == ConnectState.STATE_CONNECTED
    }

    fun getBleBindingMac(): String? {
        return SpUtilsManagement.getString(KeyPre.KEY_RING_MAC, "")
    }

    fun getRingFirm(): String {
        return SpUtilsManagement.getString(KeyPre.KEY_RING_FIRM, "")
    }

    fun getCurRingFirm(): String {
        return when(SpUtilsManagement.getString(KeyPre.KEY_RING_FIRM, "")){
            DeviceFirmType.YQ_FIRM-> "1"
            DeviceFirmType.HDU_FIRM-> "2"
            else -> "0"
        }
    }

    fun getBindRingInfo(): RingInfoBean? {
//        return SpUtilsManagement.getParcelable(KeyPre.KEY_RING_INFO, RingInfoBean::class.java)
        return SpUtilsManagement.getParcelable(KeyPre.KEY_RING_INFO)
    }

    fun updateRingInfo(user: RingInfoBean? = curRingInfoBean) {
        user?.let {
            SpUtilsManagement.putParcelable(KeyPre.KEY_RING_INFO, it)
        }
    }

    /**
     * 通知SDK绑定戒指
     */
    fun boundDeviceSuc(deviceName: String, macStr: String, result: Boolean) {
        curMac = macStr
        SpUtilsManagement.putString(KeyPre.KEY_RING_FIRM, deviceName)
        SpUtilsManagement.putString(KeyPre.KEY_RING_MAC, macStr)
        curRingInfoBean = RingInfoBean(
            ringFirm = deviceName,
            ringName = deviceName,
            ringMac = macStr,
            upTime = getTimeDateLong()
        )
        SpUtilsManagement.putParcelable(KeyPre.KEY_RING_INFO, curRingInfoBean!!)
        mConnectBleDeviceExpandListenerList.forEach {
            it.onBoundDeviceResult(macStr, result)
        }
    }

    /**
     * 2.2.4.查询当前每日活动目标
     */
    fun getCurrentActivityGoals(listener: CusSdkSettingExpandListener? = null) {
        if (!isConnect()) return
        serviceSdkCommand?.getCurrentActivityGoals(object : ActivityGoalsCallback {
            override fun ActivityGoals(bean: ActivityGoals) {
//                "bean.caloriesGlobal : ${bean.caloriesGoals}".logIx()
//                "distance:${bean.distanceGoals}".logIx()
                Log.e(
                    TAG,
                    "step:${bean.stepGoals}" + ":" + "calories:${bean.distanceGoals}" + ":" + "distance:${bean.caloriesGoals}"
                )
                listener?.onCurrentActivityGoals()
            }
        })
    }

    /**
     * 设置戒指数据同步间隔
     */
    fun setDeviceDataSyncTime(time: Int = 1, listener: CusSdkSettingExpandListener? = null) {
        if (!isConnect()) return
//        serviceSdkCommand?.setDeviceDataSyncTime(time, object : BCallback {
//            override fun result(r: Boolean) {
//                r.yes {
//                    Log.e(TAG, "上报时间间隔设置成功")
//                    listener?.onDeviceDataSyncTime(r)
//                }
//            }
//        })
    }

    /**
     * 戒指电池状态与信息
     */
    fun getDevicePowerState() {
        if (!isConnect()) return

        (getRingFirm() == DeviceFirmType.HDU_FIRM).yes {
            HDuSendCommandManage.callRemoteGetDeviceBattery(mHDuService)
        }.otherwise {
            YQiSendCommandManage.callRemoteGetDeviceBattery(serviceSdkCommand)
        }

//        curRingInfoBean?.version.isNullOrEmpty().yes {
        getDeviceFirmwareParams()
//        }

    }

    /**
     * 研强-获取硬件信息
     */
    fun getDeviceFirmwareParams() {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                DeviceManager.isConnect().yes {
                    serviceSdkCommand?.getFirmwareParams()?.apply {
                        if (platform.isNullOrEmpty() || fwmVersion.isNullOrEmpty()) return@apply
                        val ringFirm = getRingFirm()
                        curRingInfoBean?.let {
                            it.ringFirm = ringFirm
                            it.ringName = ringFirm
                            it.version = fwmVersion
                            it.vendorCode = resVersion
                            it.platform = platform
                            it.brandName = brandName
                            it.modelName = modelName
                            it.resVersion = resVersion
                            it.batteryCode = batteryCode
                            it.upTime = getTimeDateLong()
                            it.otherData = JsonUtils.toJson(this)
                        }
                        updateRingInfo()

                        mBleDeviceInfoExpandListenerList.forEach {
                            doOnUiThread { it.onGetDeviceInfo() }
                        }
                    }
                }
            }

            DeviceFirmType.HDU_FIRM -> HDuSendCommandManage.callRemoteGetDeviceInfo(mHDuService)
        }
    }

    /**
     * 重置、解绑、重启戒指
     * type:1：重置戒指2：解绑戒指4：重启戒指（即恢复出厂）
     */
    fun handleDevice(type: Int = 1) {
        serviceSdkCommand?.handleDevice(type, object : BCallback {
            override fun result(r: Boolean) {
                Log.e(TAG, "handleDevice-result:$r")
            }
        })

    }

    /**
     * 2.4.3.获取当天健康综合数据
     */
    fun getToDaysHr(delayTime: Long = -1) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                LogUtils.e(TAG, "YQ: getHealthData = start")
                doOnNewThread { getYQMultiDaysHealthData(serviceSdkCommand, 0) }
            }
            DeviceFirmType.HDU_FIRM -> {
                postIoDelay(if(delayTime > 1) delayTime else 0) {
                    LogUtils.e(TAG, "HDU: getHealthData = start")
//                    getHduToDaysHr()
                    getHduToDaysHr(1)
//                    getHduToDaysHr(12)
                }
            }
        }
    }


    /**
     * 2.4.3.获取华都当天健康综合数据
     * 1： 取得当天详细运动信息, 返回步数与睡眠  2：取得当天详细心率数据,  12: 取得当天详细体温数据
     */
    fun getHduToDaysHr(type: Int = 2, day: Int = 0) {
        if (!isConnect()) return
        HDuSendCommandManage.callRemoteGetData(
            mHDuService,
            type,
            day
        )
    }


    /**
     * 2.4.3.获取健康综合数据
     * 时间范围 0-7 （0：当天，1：前一天）
     */
    fun getSynMultiDaysHr(dayNum: Int = 0, listener: CusSynthesisHealthExpandListener? = null) {
        getYQMultiDaysHealthData(ServiceSdkCommandV2, dayNum, listener)
    }

    /**
     * 封装YQ固件的多天健康数据获取
     * @param dayNum 天数范围 0-7 （0：当天，1：前一天，以此类推）
     * @param listener 数据回调监听器
     */
    private fun getYQMultiDaysHealthData(
        serviceSdkCommandTemp: ServiceSdkCommandV2?,
        dayNum: Int,
        listener: CusSynthesisHealthExpandListener? = null
    ) {

        if (serviceSdkCommandTemp == null) return

        // 声明为可变的函数变量
        lateinit var fetchDayData: (Int) -> Unit

        // 限制天数范围为0-7
        val actualDayNum = if (dayNum > 7) 7 else dayNum

        // 如果已经有查询在进行中，则等待
        if (queryYQMultiDaysHealthDataLock.get()) {
            LogUtils.e(TAG, "YQ: Previous query still in progress, waiting...")
            return
        }

        // 创建数据列表
        val heartRateList = ArrayList<UserHeartRate>()
        val hrvList = ArrayList<UserHrv>()
        val bloodOxygenList = ArrayList<UserBloodOxygen>()
        val bodyTempList = ArrayList<UserBodyTemperature>()
        val envTempList = ArrayList<UserEnvTemperature>()
        val calorieList = ArrayList<UserCalorie>()

        // 记录已完成的天数
        var completedDays = 0

        // 定义函数实现
        fetchDayData = { currentDay: Int ->
            if (currentDay > actualDayNum) {
                // 所有天数的数据都已获取完毕
//                val heartRateListStr = JsonUtils.toJson(heartRateList)
//                val bloodListStr = JsonUtils.toJson(bloodOxygenList)
//                val bodyListStr = JsonUtils.toJson(bodyTempList)

                heartRateList.isNullOrEmpty().no {
                    val heartRateListTemp = heartRateList.filter { it.heartRate > 0 } // 过滤掉pace为0的数据
                    heartRateMultiAdd2DB(heartRateListTemp)
                }

                bloodOxygenList.isNullOrEmpty().no {
                    val bloodOxygenListTemp = bloodOxygenList.filter { it.bloodOxygen > 0 } // 过滤掉pace为0的数据
                    bloodOxygenMultiAdd2DB(bloodOxygenListTemp)
                }

                bodyTempList.isNullOrEmpty().no {
                    val bodyTempListTemp = bodyTempList.filter { it.bodyTemperature > 0 } // 过滤掉pace为0的数据
                    bodyTempMultiAdd2DB(bodyTempListTemp)
                }

                hrvList.isNullOrEmpty().no {
                    hrvMultiAdd2DB(hrvList)
                }

                calorieList.isNullOrEmpty().no {
                    calorieMultiAdd2DB(calorieList)
                }

                doOnUiThread {
                    listener?.onHeartRateDataListResult(heartRateList)
                    mCusSynthesisHealthExpandListenerList.forEach {
                        it.onHeartRateDataListResult(heartRateList)
                        it.onBloodOxygenDataListResult(bloodOxygenList)
                        it.onBodyTemperDataListResult(bodyTempList)
                    }
                }
            } else {
                // 设置锁定状态
                queryYQMultiDaysHealthDataLock.set(true)

                // 计算当前要查询的日期时间戳
                val targetTimeInMills = TimeUtils.getPreviousDayLong(getTimeDateLong(), currentDay)

                LogUtils.e(
                    TAG,
                    "YQ: getHealthData for day -$currentDay, time: ${
                        TimeUtils.getYearMonthDayHourMinute(targetTimeInMills)
                    }"
                )

                // 使用CountDownTimer处理超时
                val timer = object : CountDownTimer(QUERY_TIMEOUT, QUERY_TIMEOUT) {
                    override fun onTick(millisUntilFinished: Long) {
                        // 不需要处理中间tick
                        LogUtils.e(TAG, "YQ: onTick -$millisUntilFinished")
                    }

                    override fun onFinish() {
                        if (queryYQMultiDaysHealthDataLock.get()) {
                            LogUtils.e(TAG, "YQ: Query timeout for day -$currentDay")
                            queryYQMultiDaysHealthDataLock.set(false)
                            // 超时后继续下一天查询
                            completedDays++
                            fetchDayData(currentDay + 1)
                        }
                    }
                }

                // 启动超时计时器
                timer.start()

                serviceSdkCommandTemp?.getHealthData(
                    timeInMills = targetTimeInMills,
                    object : HealthDataCallback {
                        override fun onFinish(timeInMills: Long) {
                            // 取消超时任务
                            timer.cancel()

                            LogUtils.e(TAG, "YQ: getHealthData day -$currentDay finished at ${TimeUtils.getYearMonthDayHourMinute(timeInMills)}")

                            // 释放锁
                            queryYQMultiDaysHealthDataLock.set(false)

                            // 当前天数据获取完成，继续获取下一天
                            completedDays++
                            fetchDayData(currentDay + 1)
                        }

                        override fun onReceive(data: MutableList<HealthDataBean>) {
                            LogUtils.e(TAG, "YQ: getHealthData day -$currentDay received ${data.size} records")
                            LogUtils.e(TAG, "YQ: getHealthData day -$currentDay onReceive at ${TimeUtils.getYearMonthDayHourMinute(targetTimeInMills)}")

                            // 将当天数据添加到总数据列表中
                            data.apply {
                                if (this.isEmpty()) return

                                data.sortedBy { it.time }//按时间排序（升序）

                                for ((index, heartRateData) in this.withIndex()) {
//                            saveHealthIntegratedData(heartRateData)
                                    saveStepsRelatedData(heartRateData.time,heartRateData.date, if(index == 0) heartRateData.step else (this[index-1].step - heartRateData.step),
                                        if(index == 0) heartRateData.distance.toDouble() else (this[index-1].distance - heartRateData.distance).toDouble())

                                    if (heartRateData.hr > 0) {//心率
                                        val beanTemp = UserHeartRate()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.heartRate = heartRateData.hr
                                        heartRateList.add(beanTemp)
                                    }
                                    if (heartRateData.bo > 0) {//血氧
                                        val beanTemp = UserBloodOxygen()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.bloodOxygen = heartRateData.bo
                                        bloodOxygenList.add(beanTemp)
                                    }
                                    if (heartRateData.temp > 0) {//体温
                                        val beanTemp = UserBodyTemperature()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.bodyTemperature = heartRateData.temp
                                        bodyTempList.add(beanTemp)
                                    }
                                    if (heartRateData.envtp > 0) {//环境温度
                                        val beanTemp = UserEnvTemperature()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.envTemperature = heartRateData.envtp
                                        envTempList.add(beanTemp)
                                    }
                                    if (heartRateData.hrv > 0) {//心率变异性
                                        val beanTemp = UserHrv()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.heartRateVariability = heartRateData.hrv
                                        hrvList.add(beanTemp)
                                    }
                                    if (heartRateData.calorie > 0) {//卡路里
                                        val beanTemp = UserCalorie()
                                        beanTemp.createdTime = heartRateData.time
                                        beanTemp.calorie = heartRateData.calorie.toDouble()
                                        calorieList.add(beanTemp)
                                    }
                                }
                            }
                        }
                    })
            }
        }

        // 开始从当天(0)获取数据
        fetchDayData(0)
    }

    fun saveHealthIntegratedData(heartRateData: HealthDataBean) {
        var healthIntegratedTemp = HealthIntegratedDataRepo.instance.findByTime(heartRateData.time)
        if (healthIntegratedTemp == null) {
            healthIntegratedTemp = UserHealthIntegratedData()
            healthIntegratedTemp.createdTime = heartRateData.time
        }
        healthIntegratedTemp.hr = heartRateData.hr
        healthIntegratedTemp.hrv = heartRateData.hrv
        healthIntegratedTemp.bo = heartRateData.bo.toFloat()
        healthIntegratedTemp.tempv = heartRateData.temp
        healthIntegratedTemp.step = heartRateData.step
        healthIntegratedTemp.calorie = heartRateData.calorie
        healthIntegratedTemp.distance = heartRateData.distance
        HealthIntegratedDataRepo.instance.insert(healthIntegratedTemp)
    }

    fun saveStepsRelatedData(mTime:Long, mDate:Long =0, step:Long, distance:Double,) {//
        (step>=0 && distance>=0).yes {
            var healthIntegratedTemp = UserStepsRelatedRecordRepo.instance.findByTime(mTime)
            if (healthIntegratedTemp == null) {
                healthIntegratedTemp = UserStepsRelatedRecord()
                healthIntegratedTemp.createdTime = mTime
                healthIntegratedTemp.inDateTime =
                    TimeUtils.getYearMonthDaySeries(mDate).toLong()
                healthIntegratedTemp.macAddress = curMac
                healthIntegratedTemp.firmName = getCurRingFirm()
            }
            healthIntegratedTemp.step = step
            healthIntegratedTemp.distance = distance
            healthIntegratedTemp.timeZone = getTimeZone()
            UserStepsRelatedRecordRepo.instance.add2DB(healthIntegratedTemp)
        }
    }

    /**
     * 封装华嘟固件的多天健康数据获取
     * @param dayNum 天数范围 0-7 （0：当天，1：前一天，以此类推）
     * @param listener 数据回调监听器
     */
    private fun getHDuMultiDaysHealthData(
        serviceSdkCommandTemp: ServiceSdkCommandV2?,
        dayNum: Int,
        listener: CusSynthesisHealthExpandListener? = null
    ) {

        if (serviceSdkCommandTemp == null) return

        // 限制天数范围为0-7
        val actualDayNum = if (dayNum > 7) 7 else dayNum


    }


    suspend fun queryHealthData(dayRange: IntRange) = coroutineScope {
        isConnect().yes {
            dayRange.forEach { dayNum ->
                // 顺序执行每天查询
                val result = async(Dispatchers.IO) {
                    (getRingFirm() == DeviceFirmType.HDU_FIRM).yes {
                        queryHDuSingleDayHealth(3, dayNum)
                    }.otherwise {
                        queryYQSingleDayHealth(dayNum)
                    }
                }.await() // 关键点：等待单日完成

                LogUtils.d(TAG, "YQ: Day $dayNum 查询结果：${if (result) "成功" else "失败"}")
            }
        }
    }


    private suspend fun queryHDuSingleDayHealth(type: Int, dayNum: Int): Boolean {
        val targetTime = TimeUtils.getPreviousDayLong(getTimeDateLong(), dayNum)

        return try {
            withTimeout(QUERY_TIMEOUT) {
                val result = CompletableDeferred<Boolean>() // 新增结果等待

                queryLock.withLock {
                    if (!processingDays.add(targetTime)) {
                        LogUtils.d(TAG, "HDU: 跳过重复查询：dayNum=$dayNum")
                        return@withLock false
                    }

                    LogUtils.e(TAG, "HDU: 开始查询 | getHealthData records at ${TimeUtils.getYearMonthDayHourMinute(targetTime)}")

                    HDuSendCommandManage.callRemoteGetData(
                        mHDuService,
                        type,
                        dayNum
                    ).yes {
                        result.complete(true)
                    }.otherwise {
                        result.complete(false)
                    }
                    result.await() // 等待回调完成
                }
            }
            true
        } catch (e: Exception) {
            LogUtils.d(TAG, "YQ: Exception：dayNum=$dayNum ${e.message.toString()}")
            false
        } finally {
            processingDays.remove(targetTime)
        }
    }


    private suspend fun queryYQSingleDayHealth(dayNum: Int): Boolean {
        val targetTime = TimeUtils.getPreviousDayLong(getTimeDateLong(), dayNum)
        LogUtils.e(TAG, "YQ: 开始查询 | queryYQSingleDayHealth（）")
        return try {
            withTimeout(QUERY_TIMEOUT) {
                val result = CompletableDeferred<Boolean>() // 新增结果等待

                queryLock.withLock {
                    if (!processingDays.add(targetTime)) {
                        LogUtils.d(TAG, "YQ: 跳过重复查询：dayNum=$dayNum")
                        return@withLock false
                    }

                    LogUtils.e(TAG, "YQ: 开始查询 | getHealthData records at ${TimeUtils.getYearMonthDayHourMinute(targetTime)}")
                    serviceSdkCommand?.getHealthData(
                        targetTime,
                        createHrCallback(targetTime, result)
                    )
                    result.await() // 等待回调完成
                }
            }
            true
        } catch (e: Exception) {
            LogUtils.d(TAG, "YQ: Exception：dayNum=$dayNum ${e.message.toString()}")
            false
        } finally {
            processingDays.remove(targetTime)
        }
    }

    private fun createHrCallback(targetTime: Long, result: CompletableDeferred<Boolean>) =
        object : HealthDataCallback {

            // 创建数据列表
            val heartRateList = ArrayList<UserHeartRate>()
            val hrvList = ArrayList<UserHrv>()
            val bloodOxygenList = ArrayList<UserBloodOxygen>()
            val bodyTempList = ArrayList<UserBodyTemperature>()
            val envTempList = ArrayList<UserEnvTemperature>()
            val calorieList = ArrayList<UserCalorie>()

            override fun onReceive(data: MutableList<HealthDataBean>) {
                LogUtils.e(TAG, "YQ: 接收健康综合数据 | getHealthData day - ${data.size} records at ${TimeUtils.getYearMonthDayHourMinute(targetTime)}")

                // 将当天数据添加到总数据列表中
                data?.apply {
                    if (this.isEmpty()) return
                    for ((index, heartRateData) in this.withIndex()) {
//                    for (heartRateData in this) {
                        saveStepsRelatedData(heartRateData.time,heartRateData.date, if(index == 0) heartRateData.step else (this[index-1].step - heartRateData.step),
                            if(index == 0) heartRateData.distance.toDouble() else (this[index-1].distance - heartRateData.distance).toDouble())

                        if (heartRateData.hr > 0) {//心率
                            val beanTemp = UserHeartRate()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.heartRate = heartRateData.hr
                            heartRateList.add(beanTemp)
                        }
                        if (heartRateData.bo > 0) {//血氧
                            val beanTemp = UserBloodOxygen()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.bloodOxygen = heartRateData.bo
                            bloodOxygenList.add(beanTemp)
                        }
                        if (heartRateData.temp > 0) {//体温
                            val beanTemp = UserBodyTemperature()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.bodyTemperature = heartRateData.temp
                            bodyTempList.add(beanTemp)
                        }
                        if (heartRateData.envtp > 0) {//环境温度
                            val beanTemp = UserEnvTemperature()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.envTemperature = heartRateData.envtp
                            envTempList.add(beanTemp)
                        }

                        if (heartRateData.hrv > 0) {//心率
                            val beanTemp = UserHrv()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.heartRateVariability = heartRateData.hrv
                            hrvList.add(beanTemp)
                        }

                        if (heartRateData.calorie > 0) {//卡路里
                            val beanTemp = UserCalorie()
                            beanTemp.createdTime = heartRateData.time
                            beanTemp.calorie = heartRateData.calorie.toDouble()
                            calorieList.add(beanTemp)
                        }
                    }

                    heartRateList.isNullOrEmpty().no {
                        heartRateMultiAdd2DB(heartRateList)
                    }
                    bloodOxygenList.isNullOrEmpty().no {
                        bloodOxygenMultiAdd2DB(bloodOxygenList)
                    }
                    bodyTempList.isNullOrEmpty().no {
                        bodyTempMultiAdd2DB(bodyTempList)
                    }
                    hrvList.isNullOrEmpty().no {
                        hrvMultiAdd2DB(hrvList)
                    }
                    calorieList.isNullOrEmpty().no {
                        calorieMultiAdd2DB(calorieList)
                    }


//                doOnUiThread {
//                    mBleDeviceDataExpandListenerList.forEach {
//                        it.onHeartRateDataListResult(heartRateList)
//                        it.onBloodOxygenDataListResult(bloodOxygenList)
//                        it.onBodyTemperDataListResult(bodyTempList)
//                    }
//                }
                }
            }

            override fun onFinish(timeInMills: Long) {
                runCatching {
//                JsonUtils.toJson(heartRateList)
                    LogUtils.e(
                        TAG,
                        "YQ: 健康综合完成查询 | getHealthData day -${
                            TimeUtils.getYearMonthDayHourMinute(targetTime)
                        } finished at ${TimeUtils.getYearMonthDayHourMinute(timeInMills)} size at ${heartRateList.size}"
                    )
                }.onSuccess {
//                JsonUtils.toJson(heartRateList)
                    val uniqueSleepInfo = heartRateList.toSet().toMutableList()//去重
                    LogUtils.e(
                        TAG,
                        "YQ: 健康综合完成查询 | getHealthData day onSuccess-${
                            TimeUtils.getYearMonthDayHourMinute(targetTime)
                        } finished at ${TimeUtils.getYearMonthDayHourMinute(timeInMills)} size at ${uniqueSleepInfo.size}"
                    )
                    result.complete(true)
                }.onFailure {
                    result.completeExceptionally(it)
                }
            }
        }


    fun queryYQSingleDaySleepDatas(dayNum: Int) {
        val targetTime = TimeUtils.getPreviousDayLong(getTimeDateLong(), dayNum)
        LogUtils.e(
            TAG,
            "YQ: 开始睡眠查询 | querySingleDaySleepData records at ${
                TimeUtils.getYearMonthDayHourMinute(targetTime)
            }"
        )
        serviceSdkCommand?.getSleepData(
            targetTime,
            createSleepCallback(targetTime, CompletableDeferred())
        )
    }

    suspend fun querySleepData(dayRange: IntRange) = coroutineScope {
        isConnect().yes {
            dayRange.forEach { dayNum ->
                // 顺序执行每天查询
                val result = async(Dispatchers.IO) {

                    (getRingFirm() == DeviceFirmType.HDU_FIRM).yes {
                        queryHDuSingleDayHealth(1, dayNum)
                    }.otherwise {
                        queryYQSingleDaySleepData(dayNum)
                    }
                }.await() // 关键点：等待单日完成

                LogUtils.d(TAG, "YQ: Day $dayNum 查询结果：${if (result) "成功" else "失败"}")
            }
        }
    }

    suspend fun queryYQSingleDaySleepData(dayNum: Int): Boolean {
        val targetTime = TimeUtils.getPreviousDayLong(getTimeDateLong(), dayNum)

        return try {
            withTimeout(QUERY_TIMEOUT) {
                val result = CompletableDeferred<Boolean>() // 新增结果等待

                queryLock.withLock {
                    if (!processingDays.add(targetTime)) {
                        LogUtils.d(TAG, "YQ: 跳过重复睡眠查询：dayNum=$dayNum")
                        return@withLock false
                    }

                    LogUtils.e(
                        TAG,
                        "YQ: 开始睡眠查询 | querySingleDaySleepData records at ${
                            TimeUtils.getYearMonthDayHourMinute(targetTime)
                        }"
                    )
                    serviceSdkCommand?.getSleepData(
                        targetTime,
                        createSleepCallback(targetTime, result)
                    )
                    result.await() // 等待回调完成
                }
            }
            true
        } catch (e: Exception) {
            LogUtils.d(TAG, "YQ: Exception：dayNum=$dayNum ${e.message.toString()}")
            false
        } finally {
            processingDays.remove(targetTime)
        }
    }

    private fun createSleepCallback(targetTime: Long, result: CompletableDeferred<Boolean>) =
        object : SleepDataCallback {

            override fun sleepData(bean: MutableList<SleepRecord>) {
                LogUtils.e(
                    TAG,
                    "YQ: 收到睡眠数据数量 | getSleepData day - ${bean.size} records at ${
                        TimeUtils.getYearMonthDayHourMinute(targetTime)
                    }"
                )

                bean.forEach {
                    LogUtils.e(
                        TAG,
                        "YQ: 收到睡眠数据数量 | getSleepData day - records at sleepDetails ${it.sleepDetails.size} "
                    )
                    when(it.sleepType){//睡眠类型，0-夜间睡眠，1-零星小睡
                        0->{
                            it.sleepDetails.forEach { sleepDetailsIt ->
                                val userSleepInfo = UserSleepInfo()
                                userSleepInfo.sleepType = it.sleepType
                                userSleepInfo.createdTime = sleepDetailsIt.time
                                userSleepInfo.sleepQuality =
                                    when (sleepDetailsIt.mode) {//1 浅睡阶段 2 深睡阶段 3 清醒阶段 4 未佩戴 5 快速眼动
                                        1 -> SleepModeType.LIGHT.value
                                        2 -> SleepModeType.DEEP.value
                                        3 -> SleepModeType.WAKE.value
                                        4 -> SleepModeType.NOT_WEARING.value
                                        5 -> SleepModeType.REM.value
                                        else -> -1//无效数据
                                    }
                                sleepTempAdd2DB(userSleepInfo)
                            }
                        }
                        1->{//睡眠类型，0-夜间睡眠，1-零星小睡
                            val userSleepInfo = UserSleepInfo()
                            userSleepInfo.createdTime = it.startTime
                            userSleepInfo.endTime = it.endTime
                            userSleepInfo.sleepType = it.sleepType
                            sleepTempAdd2DB(userSleepInfo)
                        }
                    }

                }
                result.complete(true)
                LogUtils.e(TAG, "YQ: 收到睡眠数据 : ${bean.toFastJson()}")
            }
        }

    /**
     * 2.6.1.获取睡眠评分
     */
    fun getSleepScore(
        time: Long = getTimeDateLong(),

        ) {
        if (!isConnect()) return
//        serviceSdkCommand?.getSleepScore(time = time, object : SleepScoreCallback {
//            override fun sleepScore(bean: SleepScore) {
////                listener?.onBodyTemperDataListResult(resultList)
//            }
//        })
    }

    /**
     * 2.4.11.立即测量/结束 心率/血氧/体温等健康指标数据
     * type: 测量类型，如心率、血氧、体温（1心率 2血氧 6体温）operation: int, 开始测量, 取消测量（1开始测量，2结束测量）
     *
     * measureResult:result: true-成功，false-失败 type: 测量类型，如01心率、02血氧、03体温 time: long,
     * 测量数据时间戳 heartrate: int, 40~220 bloodoxygen: int,1-100 bodytemp: float, 体温，26.0~42.0 envtemp: float, 体温，26.0~42.0
     * 注： 1）如果失败，则返回失败和测量类型；如果成功则还需要返回测量时间和测量结果数据；
     * 2）结果数据heartrate,bloodoxygen,bodytemp三者每次只能测量一个，当非测量时，返回值为-1，-1， 0.0。如测量血氧时，返回数据为 -1, 98，0.0
     *
     * 注：每次测量只能测量一种健康数据指标，不能并发测量，必须等前一次测量结束才能测量下一个健康指标数据。
     */
    fun instantMeasurement(mType: Int, operation: Int = 1) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                Log.e(TAG, "YQ: instantMeasurement ： 测量方法执行！")
                serviceSdkCommand?.instantMeasurement(
                    mType,
                    operation,
                    object : MeasureResultCallback {
                        override fun measureResult(bean: MeasureResult) {
                            bean.result.yes {
                                when (mType) {
                                    CommonCusHealthType.HEARTRATE.value -> {
                                        val mHeartRate = UserHeartRate()
                                        mHeartRate.createdTime = bean.time
                                        mHeartRate.heartRate = bean.heartrate
                                        heartRateRepoAdd2DB(mHeartRate)
                                    }

                                    CommonCusHealthType.BLOODOXYGEN.value -> {
                                        val mBloodOxygen = UserBloodOxygen()
                                        mBloodOxygen.createdTime = bean.time
                                        mBloodOxygen.bloodOxygen = bean.bloodoxygen
                                        bloodOxygenAdd2DB(mBloodOxygen)
                                    }

                                    CommonCusHealthType.BODYTEMP.value -> {
                                        val mBodyTempe = UserBodyTemperature()
                                        mBodyTempe.createdTime = bean.time
                                        mBodyTempe.bodyTemperature = bean.bodytemp
                                        bodyTempAdd2DB(mBodyTempe)
                                    }
                                    else -> {}
                                }
                            }

                            mCusSynthesisHealthExpandListenerList.forEach {
                                it.onMeasureResult(
                                    bean.result,
                                    bean.type,
                                    bean.time,
                                    bean.heartrate,
                                    bean.bloodoxygen,
                                    bean.bodytemp,
                                    bean.envtemp
                                )
                            }
                        }

                    })
            }

            DeviceFirmType.HDU_FIRM -> {
                when (mType) {
                    CommonCusHealthType.HEARTRATE.value -> {
                        HDuSendCommandManage.callRemoteSetHeartRateMode(mHDuService, (operation == 1))
                    }

                    CommonCusHealthType.BLOODOXYGEN.value -> {
                        HDuSendCommandManage.callRemoteOpenBlood(mHDuService, (operation == 1))
                    }

                    CommonCusHealthType.BODYTEMP.value -> {
                    }
                }
            }
        }
    }

    /**
     * 暂停运动总入口
     */
    fun setCusSportPause(sportType: Int = 0, sportId: Long = 0) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.sportPause(sportType, sportId, object : ICallback {
                    override fun result(r: Int) {
                        mSportMonitorDataExpandListenerList.forEach {
                            it.sportPause(true)
                        }
                    }

                })
            }
            DeviceFirmType.HDU_FIRM ->{
                // 回调给外层
                doOnUiThread {
                    mSportMonitorDataExpandListenerList.forEach {
                        it.sportPause(true)
                    }
                }

            }
        }
    }

    /**
     * 恢复运动总入口
     */
    fun setCusSportResume(sportType: Int = 0, sportId: Long = 0) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.sportResume(sportType, sportId, object : ICallback {
                    override fun result(r: Int) {
                        (r == 1).yes {
                            mSportMonitorDataExpandListenerList.forEach {
                                it.sportResume(true)
                            }
                        }.otherwise {
                            ToastUtils.showToast("恢复运动失败，请重试！")
                        }
                    }
                })
            }
            DeviceFirmType.HDU_FIRM ->{
                // 回调给外层
                doOnUiThread {
                    mSportMonitorDataExpandListenerList.forEach {
                        it.sportResume(true)
                    }
                }

            }
        }
    }

    /**
     * 停止运动总入口
     */
    fun setCusSportStop(
        sportType: Int = 0,
        sportId: Long = 0,
        callback: ((Boolean) -> Unit)? = null
    ) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.sportStop(sportType, sportId, object : ICallback {
                    override fun result(r: Int) {
                        (r == 1).yes {
                            if (callback == null) {
                                mSportMonitorDataExpandListenerList.forEach {
                                    it.sportStop(true)
                                }
                            }
                        }.otherwise {
                            ToastUtils.showToast("停止运动失败，请重试！")
                        }
                        callback?.invoke((r == 1))
                    }
                }, object : SportRecordCallback {
                    override fun onSportRecord(record: SportRecord?) {
                        saveSportRecord(record)
                    }

                })
            }
            DeviceFirmType.HDU_FIRM ->{
                mHduSportMonitorTask = null
                mSportMonitorDataExpandListenerList.forEach {
                    it.sportStop(true)
                }
                // 回调给外层
                doOnUiThread {
                    callback?.invoke((true))
                }

            }
        }
    }

    /**
     * 研强-获取运动状态（判断当前是否有运动任务进行中）
     *SportType:
     *| 0x09     | 室外健走   | 9   |
     *| 0x0A     | 室外跑步   | 10  |
     *| 0x0B     | 室外骑行   | 11  |
     *| 0x07     | 室内健走   | 7   |
     *| 0x08     | 室内跑步   | 8   |
     *| 0x05     | 室内骑行   | 5   |
     * sportId:开始运动传入的时间戳作为Id
     */
    fun checkSportStatus(callback: ((Int, Long, Int) -> Unit)? = null) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.getSportStatus(object :
                    SportStatusCallback {

                    override fun status(bean: SportStatus) {
                        // 回调给外层
                        doOnUiThread {
                            callback?.invoke(bean.sportStatus, bean.sportId, bean.sportType)
                        }
                    }

                })
            }
            DeviceFirmType.HDU_FIRM ->{
                // 回调给外层
                doOnUiThread {
                    callback?.invoke(0, 0, 0)
                }

            }
        }
    }

    /**
     * 研强-运动复位
     *SportType:
     *| 0x09     | 室外健走   | 9   |
     *| 0x0A     | 室外跑步   | 10  |
     *| 0x0B     | 室外骑行   | 11  |
     *| 0x07     | 室内健走   | 7   |
     *| 0x08     | 室内跑步   | 8   |
     *| 0x05     | 室内骑行   | 5   |
     * sportId:开始运动传入的时间戳作为Id
     */
    fun getYQSportStopAndGetRecord(
        sportId: Long,
        sportType: Int,
        onResult: ((Boolean) -> Unit)? = null,
        onSportRecord: ((SportRecord?) -> Unit)? = null
    ) {
        if (!isConnect()) return
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> serviceSdkCommand?.sportStopAndGetRecord(
                sportId,
                sportType,
                object :
                    ICallback {
                    override fun result(r: Int) {
                        (r == 1).yes {
                            // 回调给外层
//                        callback?.invoke(true)
                        }.otherwise {
                            Log.e(TAG, "YQ: sportStopAndGetRecord ： 停止运动失败！")
                        }
                        doOnUiThread { onResult?.invoke(true) }
                    }
                },
                object : SportRecordCallback {
                    override fun onSportRecord(record: SportRecord?) {
                        saveSportRecord(record)
                        doOnUiThread { onSportRecord?.invoke(record) }
                        LogUtils.e(
                            TAG, "YQ: sportStopAndGetRecord ： onSportRecord${
                                record?.let {
                                    JsonUtils.toJson(
                                        it
                                    )
                                }
                            }"
                        )
                    }
                })
        }
    }

    /**
     * 研强-运动开始
     *SportType:
     *| 0x09     | 室外健走   | 9   |
     *| 0x0A     | 室外跑步   | 10  |
     *| 0x0B     | 室外骑行   | 11  |
     *| 0x07     | 室内健走   | 7   |
     *| 0x08     | 室内跑步   | 8   |
     *| 0x05     | 室内骑行   | 5   |
     * sportId:开始运动传入的时间戳作为Id
     */
    fun setSportStart(sportType: Int, sportId: Long) {
        if (!isConnect()) return
        when (val mRingFirm = getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.sportStart(
                    sportType,
                    sportId,
                    object : ICallback {
                        override fun result(r: Int) {
                            (r == 1).yes {
                                constructionSportRecord(sportId,sportType,mRingFirm)
                                Log.e(TAG, "YQ: sportStart ： 开始运动后需每5秒主动查询获取运动数据！")
                            }.otherwise {
                                Log.e(TAG, "YQ: sportStart ： 开始运动失败！")
                                mSportMonitorDataExpandListenerList.forEach {
                                    it.sportStart(false, 0,mRingFirm)
                                }
                            }
                        }
                    })
            }
            DeviceFirmType.HDU_FIRM -> {
                constructionSportRecord(sportId,sportType,mRingFirm)
                mHduSportMonitorTask = SportMonitorTask().apply { mSportId = sportId; mSportType = sportType; hudDuringExercise = true}
            }
        }
    }

    /**
     * 构造开始运动时记录
     */
    fun constructionSportRecord(sportId:Long,sportType:Int, ringFirm: String){
        mSportMonitorDataExpandListenerList.forEach {
            it.sportStart(true, sportId,ringFirm)
        }
//        var mSportRecord = SportRecordRepo.instance.findByTime(sportId)
//        if (mSportRecord == null) {
//            mSportRecord = UserSportRecord()
//            mSportRecord.startTs = sportId
//            mSportRecord.sportType = sportType
//            mSportRecord.device = curMac
//            mSportRecord.firmName = getCurRingFirm()
//            mSportRecord.timeZone = getTimeZone()
//            mSportRecord.date = TimeUtils.getYearMonthDayHourMin(sportId)
//            SportRecordRepo.instance.add2DB(mSportRecord)
//        }
    }

    /**
     * 获取正在运动的实时数据
     */
    fun getYQSportDetail(sportType: Int, sportId: Long) {
//        if (!isConnect()) return
//        serviceSdkCommand?.getSportDetail(object :
//                SportDetailCallback {
//                override fun onSportDetail(detail: SportDetail) {
//                    TODO("Not yet implemented")
//                }
//            })
    }

    /**
     * 研强-获取运动综合数据
     */
    fun getYQSportRecord(callback: (() -> Unit)? = null) {
        if (!isConnect()) return
        Log.e(TAG, "YQ: getYQSportRecord ： 获取运动综合数据！")
        serviceSdkCommand?.getSportRecord(object : SportRecordCallback {
            override fun onSportRecord(record: SportRecord?) {
                saveSportRecord(record)
                callback?.invoke()
            }
        })
    }


    /**
     * 获取运动实时运动数据
     */
    fun getCusSportLiveData(
        sportType: Int,
        sportId: Long,
        callback: ((Double, Int, Double, Int) -> Unit)? = null
    ) {
        if (!isConnect()) return
        Log.e(TAG, "YQ: getCusSportLiveData ： 获取运动实时运动数据！")
        when (getRingFirm()) {
            DeviceFirmType.YQ_FIRM -> {
                serviceSdkCommand?.getSportLiveData(sportType, sportId, object : SportLiveDataCallback {
                    override fun onSportLiveData(liveData: SportLiveData) {
                        callback?.invoke(
                            liveData.dist.toDouble() / 1000,
                            liveData.hr,
                            liveData.calorie.toDouble(),
                            liveData.step.toInt()
                        )
                    }
                })
            }
            DeviceFirmType.HDU_FIRM ->{
                mHduSportMonitorTask?.getSportLiveData { km, hr, kcal, realStep ->
                    // 回调给外层
                    doOnUiThread {
                        callback?.invoke(km, hr, kcal, realStep)
                    }
                }

            }
        }
    }

    /**
     * 保存更新运动记录
     */
    fun saveSportRecord(record: SportRecord?) {
        record?.let {
            if (record.duration < 180) return//小于三分钟的数据不入库
            var mSportRecord = SportRecordRepo.instance.findByTime(record.sportId)
            if (mSportRecord == null) {
                mSportRecord = UserSportRecord()
            }
            mSportRecord.startTs = it.sportId
            mSportRecord.endTs = it.endTime
            mSportRecord.sportType = it.sportType
            mSportRecord.stages = JsonUtils.toJson(it.sportDetails)
            mSportRecord.device = curMac
            mSportRecord.steps = it.steps
            mSportRecord.duration = it.duration
            mSportRecord.calories = it.calorie
            mSportRecord.distance = it.distance
            mSportRecord.hrAvg = it.avgHr
            mSportRecord.hrMin = it.minHr
            mSportRecord.hrMax = it.maxHr

            mSportRecord.paceAvg =
                it.avgPace//就逻辑 double.parse(((pacemax + pacemin) / 2).toStringAsFixed(2)),
            mSportRecord.paceMax = it.maxPace
            mSportRecord.paceMin = it.minPace
            mSportRecord.sfAvg = it.avgCadence.toDouble()

            mSportRecord.deviceId = getBindRingInfo()?.id.toString()
            mSportRecord.firmName = getCurRingFirm()
            mSportRecord.timeZone = getTimeZone()
            mSportRecord.date = TimeUtils.getYearMonthDayHourMin(it.sportId)
            SportRecordRepo.instance.add2DB(mSportRecord)
        }
    }

    /**
     * 单条心率数据入库
     */
    private fun addEntryTimeDB(time: Long, mType: Int) {
        if (time <= 0) return
        val timeTamp = TimeUtils.getYearMonthDay(time)
        var mHeartEntryTime = HeartEntryTimeRepo.instance.findByTime(timeTamp)
        if (mHeartEntryTime == null) {
            mHeartEntryTime = UserHeartEntryTime()
            mHeartEntryTime.createdTime = timeTamp
        }
        when (mType) {
            CommonCusHealthType.HEARTRATE.value -> mHeartEntryTime.hasHeartRate = 1
            CommonCusHealthType.BLOODOXYGEN.value -> mHeartEntryTime.hasBloodOxygen = 1
            CommonCusHealthType.BODYTEMP.value -> mHeartEntryTime.hasBodyTemperature = 1
            CommonCusHealthType.SLEEP.value -> mHeartEntryTime.hasSleepInfo = 1
            CommonCusHealthType.SPORTS.value -> mHeartEntryTime.hasSports = 1

            CommonCusHealthType.HRV.value -> mHeartEntryTime.hasHrv = 1
            CommonCusHealthType.CALORIE.value -> mHeartEntryTime.hasCalorie = 1
            CommonCusHealthType.STRESS.value -> mHeartEntryTime.hasStress = 1
            CommonCusHealthType.STAND.value -> mHeartEntryTime.hasStand = 1
            CommonCusHealthType.BREATH.value -> mHeartEntryTime.hasBreath = 1
        }

        mHeartEntryTime.firmName = getCurRingFirm()
        mHeartEntryTime.timeZone = getTimeZone()
        HeartEntryTimeRepo.instance.add2DB(mHeartEntryTime)
    }

    /**
     * 单条心率数据入库
     */
    fun heartRateRepoAdd2DB(mData: UserHeartRate) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        HeartRateRepo.instance.add2DB(mData)
//        if (getRingFirm() == DeviceFirmType.HDU_FIRM) instantMeasurement(CommonCusHealthType.BLOODOXYGEN.value)//华嘟每进行一次心率都主动触发一次血氧检测
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.HEARTRATE.value)
    }

    /**
     * 单条血氧数据入库
     */
    fun bloodOxygenAdd2DB(mData: UserBloodOxygen) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        BloodOxygenRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.BLOODOXYGEN.value)
    }

    /**
     * 单条体温数据入库
     */
    fun bodyTempAdd2DB(mData: UserBodyTemperature) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        BodyTemperatureRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.BODYTEMP.value)
    }

    /**
     * 单条睡眠数据入库
     */
    fun sleepTempAdd2DB(mData: UserSleepInfo) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        SleepInfoRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.SLEEP.value)
    }

    /**
     * 单条心率变异性数据入库
     */
    fun hrvTempAdd2DB(mData: UserHrv) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        HeartRateVariabilityRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.HRV.value)
    }

    /**
     * 单条活动强度数据入库
     */
    fun acLevelTempAdd2DB(mData: UserAcLevel) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        UserAcLevelRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.HRV.value)
    }

    /**
     * 单条卡路里数据入库
     */
    fun calorieMultiAdd2DB(mData: UserCalorie) {
        mData.firmName = getCurRingFirm()
        mData.timeZone = getTimeZone()
        mData.macAddress = curMac
        mData.inDateTime = TimeUtils.getYearMonthDaySeries(mData.createdTime).toLong()
        mData.timeZone = getTimeZone()
        UserCalorieRepo.instance.add2DB(mData)
        addEntryTimeDB(mData.createdTime, CommonCusHealthType.CALORIE.value)
    }

    /**
     * 多条心率数据入库
     */
    fun heartRateMultiAdd2DB(mList: List<UserHeartRate>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.HEARTRATE.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            val heartRateListTemp = mList.filter { it.heartRate > 0 } // 过滤掉pace为0的数据
            HeartRateRepo.instance.insertDistinct(heartRateListTemp)
        }
    }

    /**
     * 多条血氧数据入库
     */
    fun bloodOxygenMultiAdd2DB(mList: List<UserBloodOxygen>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.BLOODOXYGEN.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            val bloodOxygenListTemp = mList.filter { it.bloodOxygen > 0 } // 过滤掉pace为0的数据
            BloodOxygenRepo.instance.insertDistinct(bloodOxygenListTemp)
        }
    }

    /**
     * 多条体温数据入库
     */
    fun bodyTempMultiAdd2DB(mList: List<UserBodyTemperature>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.BODYTEMP.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            val bodyTempListTemp = mList.filter { it.bodyTemperature > 0 } // 过滤掉pace为0的数据
            BodyTemperatureRepo.instance.insertDistinct(bodyTempListTemp)
        }
    }

    /**
     * 多条睡眠数据入库
     */
    fun sleepMultiAdd2DB(mList: List<UserSleepInfo>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.SLEEP.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            val sleepTempListTemp = mList.filter { it.sleepQuality > -1 } // 过滤掉pace为空的数据
            SleepInfoRepo.instance.insertDistinct(sleepTempListTemp,1000)
        }
    }

    /**
     * 多条心率变异性数据入库
     */
    fun hrvMultiAdd2DB(mList: List<UserHrv>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.HRV.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            HeartRateVariabilityRepo.instance.insertDistinct(mList,1000)
        }
    }

    /**
     * 多条卡路里数据入库
     */
    fun calorieMultiAdd2DB(mList: List<UserCalorie>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.CALORIE.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            UserCalorieRepo.instance.insertDistinct(mList,1000)
        }
    }

    /**
     * 多条压力数据入库
     */
    fun stressMultiAdd2DB(mList: List<UserStress>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.STRESS.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            UserStressRepo.instance.insertDistinct(mList,1000)
        }
    }

    /**
     * 多条站立数据入库
     */
    fun standMultiAdd2DB(mList: List<UserStand>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.STAND.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            UserStandRepo.instance.insertDistinct(mList,1000)
        }
    }

    /**
     * 多条呼吸率数据入库
     */
    fun breathMultiAdd2DB(mList: List<UserRespiratoryRate>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.BREATH.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            RespiratoryRateRepo.instance.insertDistinct(mList,1000)
        }
    }

    /**
     * 多条运动数据入库
     */
    fun sportsMultiAdd2DB(mList: List<UserSportRecord>) {
        mList.forEach {
            addEntryTimeDB(it.startTs, CommonCusHealthType.SPORTS.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            val sportTempListTemp = mList.filter { it.sportType > -2 }.filter { it.duration > 180 }  // 过滤掉pace为空的数据；运动时长少于三分钟的数据
            SportRecordRepo.instance.insertDistinct(sportTempListTemp,1000)
        }
    }

    /**
     * 多条活动强度数据入库
     */
    fun acLevelMultiAdd2DB(mList: List<UserAcLevel>) {
        mList.forEach {
            addEntryTimeDB(it.createdTime, CommonCusHealthType.BREATH.value)
            it.macAddress = curMac
            it.firmName = getCurRingFirm()
            it.inDateTime = TimeUtils.getYearMonthDaySeries(it.createdTime).toLong()
            it.timeZone = getTimeZone()
        }

        mList.isNullOrEmpty().no {
            UserAcLevelRepo.instance.insertDistinct(mList,1000)
        }
    }
}